from . import admin_bp
from flask import request, jsonify
from datetime import datetime, timedelta
from app.models import User
from app.extensions import db
from app.decorator import permission_required
from app.models import ModuleType, OperationType

<<<<<<< HEAD
@admin_bp.route('/admin/home/total',methods=['GET'])
=======

@admin_bp.route('/admin/home/total', methods=['GET'])
>>>>>>> 7245172afa54706ac2f9973f27248496e8835d1c
@permission_required(ModuleType.ADMIN_USER, OperationType.QUERY)
def user_total():
    # 获取总用户数
    user_count = User.query.count()
<<<<<<< HEAD
    
=======

>>>>>>> 7245172afa54706ac2f9973f27248496e8835d1c
    # 获取今日新增用户数
    today = datetime.now().date()
    today_new = User.query.filter(
        db.func.date(User.create_time) == today
    ).count()
<<<<<<< HEAD
    
=======

>>>>>>> 7245172afa54706ac2f9973f27248496e8835d1c
    data = {
        'total': user_count,
        'new_user': today_new
    }
<<<<<<< HEAD
    
    
    return jsonify({'message':'获取用户统计成功','errcode':'0','data':data}),200

@admin_bp.route('/admin/home/new_user_echarts',methods=['GET'])
=======

    return jsonify({'message': '获取用户统计成功', 'errcode': '0', 'data': data}), 200


@admin_bp.route('/admin/home/new_user_echarts', methods=['GET'])
>>>>>>> 7245172afa54706ac2f9973f27248496e8835d1c
@permission_required(ModuleType.ADMIN_USER, OperationType.QUERY)
def new_user_echarts():
    # 获取日期参数，格式为 "YYYY-MM"
    month_param = request.args.get('month')
<<<<<<< HEAD
    
    if not month_param:
        return jsonify({'message':'缺少参数month','errcode':'-1'}),400
    
    try:
        # 解析年份和月份
        year, month = map(int, month_param.split('-'))
        start_date = datetime(year, month, 1)
        if month == 12:
            end_date = datetime(year + 1, 1, 1)
            last_day = datetime(year, month, 31)
        else:
            end_date = datetime(year, month + 1, 1)
            last_day = end_date - timedelta(days=1)
            
        dates = []
        values = []
        current_date = start_date
        while current_date <= last_day:
            dates.append(current_date.strftime('%Y-%m-%d'))
            values.append(0)
            current_date += timedelta(days=1)

        new_users = db.session.query(
            db.func.date(User.create_time).label('date'),
            db.func.count(User.id).label('count')
        ).filter(
            User.create_time >= start_date,
            User.create_time < end_date
        ).group_by(
            db.func.date(User.create_time)
        ).all()

=======

    if not month_param:
        return jsonify({'message': '缺少参数month', 'errcode': '-1'}), 400

    try:
        # 解析年份和月份
        year, month = map(int, month_param.split('-'))
        start_date = datetime(year, month, 1)
        if month == 12:
            end_date = datetime(year + 1, 1, 1)
            last_day = datetime(year, month, 31)
        else:
            end_date = datetime(year, month + 1, 1)
            last_day = end_date - timedelta(days=1)

        dates = []
        values = []
        current_date = start_date
        while current_date <= last_day:
            dates.append(current_date.strftime('%Y-%m-%d'))
            values.append(0)
            current_date += timedelta(days=1)

        new_users = db.session.query(
            db.func.date(User.create_time).label('date'),
            db.func.count(User.id).label('count')
        ).filter(
            User.create_time >= start_date,
            User.create_time < end_date
        ).group_by(
            db.func.date(User.create_time)
        ).all()

>>>>>>> 7245172afa54706ac2f9973f27248496e8835d1c
        for date, count in new_users:
            date_str = date.strftime('%Y-%m-%d')
            if date_str in dates:
                index = dates.index(date_str)
                values[index] = count
<<<<<<< HEAD
        
=======

>>>>>>> 7245172afa54706ac2f9973f27248496e8835d1c
        data = {
            'dates': dates,
            'values': values
        }
<<<<<<< HEAD
        
        return jsonify({'message':'获取新用户统计成功','errcode':'0','data':data}),200
    
    except ValueError:
        return jsonify({'message':'日期格式错误，请使用YYYY-MM格式','errcode':'-1'}),400
    
    
=======

        return jsonify({'message': '获取新用户统计成功', 'errcode': '0', 'data': data}), 200

    except ValueError:
        return jsonify({'message': '日期格式错误，请使用YYYY-MM格式', 'errcode': '-1'}), 400
>>>>>>> 7245172afa54706ac2f9973f27248496e8835d1c
